//
//  DJIVideoViewController.m
//  DJIVideo
//
//  Created by wenpd on 2021/4/6.
//

#import "DJIVideoViewController.h"
#import "ReactiveObjC.h"
#import "Pub_Defines.h"
#import "Constants.h"
#import "VideoPreviewerSDKAdapter.h"
#import "WebSocketManager.h"

#import <DJISDK/DJISDK.h>
#import <DJIWidget/DJIVideoPreviewer.h>
#import <DJILogin_Category/CTMediator+DroneManager.h>
#import <Masonry/Masonry.h>
#import <QBUtility/ZQLog.h>

@interface DJIVideoViewController ()

@property(nonatomic) UIView* videoPreviewView;
@property(nonatomic) VideoPreviewerSDKAdapter* previewerAdapter;

@end

@implementation DJIVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initView];
    [self initProperty];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initView{
    [ZQLog bLogI:@"Enter preview"];
    self.videoPreviewView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.videoPreviewView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.videoPreviewView];
    [self.view sendSubviewToBack:self.videoPreviewView];
    
    [self switchVideoFeed:NO];
    
    _btnsView = [[ButtonsViewController alloc]init];
    _btnsView.delegate = self;
    [self.view addSubview:_btnsView.view];
    [self addChildViewController:_btnsView];
    [_btnsView.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.view.mas_centerY).offset(0);
        make.left.mas_equalTo(self.view.mas_left).offset(10);
        make.height.mas_equalTo(360);
    }];
}

- (void)initProperty{
    RACSignal * signal = [[CTMediator sharedInstance] DJIDroneManager_aircraftSingal];
    WeakRef(weakSelf);
    [signal subscribeNext:^(id  _Nullable x) {
        //无人机连接断开
        if(!x) {
            if(weakSelf.previewerAdapter) {
                [weakSelf.previewerAdapter stop];
                weakSelf.previewerAdapter = nil;
                [[DJIVideoPreviewer instance] unSetView];
                [[DJIVideoPreviewer instance] close];
            }
        }
    }];
}

- (void)switchVideoFeed:(BOOL)isFpv{
    if(self.previewerAdapter) {
        [self.previewerAdapter stop];
        self.previewerAdapter = nil;
    }
    
    [DJIVideoPreviewer instance].type = DJIVideoPreviewerTypeAutoAdapt;
    [[DJIVideoPreviewer instance] start];
    [[DJIVideoPreviewer instance] reset];
    [[DJIVideoPreviewer instance] setView:self.videoPreviewView];
    [[DJIVideoPreviewer instance] setEnableHardwareDecode:YES];
    
    DJIVideoFeed *videoFeed = isFpv?[DJISDKManager videoFeeder].secondaryVideoFeed:[DJISDKManager videoFeeder].primaryVideoFeed;
    self.previewerAdapter = [VideoPreviewerSDKAdapter adapterWithVideoPreviewer:[DJIVideoPreviewer instance] andVideoFeed:videoFeed];
    [self.previewerAdapter start];
    [self.previewerAdapter setupFrameControlHandler];
    self.previewerAdapter.delegate = self;
    
}

- (void)viewDidDisappear:(BOOL)animated{
    [[DJIVideoPreviewer instance] unSetView];
}

- (void)viewDidAppear:(BOOL)animated{
    [[DJIVideoPreviewer instance] setView:self.videoPreviewView];
}

- (void)changSource:(BOOL)toFpv {
    [self switchVideoFeed:toFpv];
}

- (void)showSettingDialog {
    if(_dlgView && [_dlgView.view isDescendantOfView:self.view]) {
        NSLog(@"Setting dialong is in showing!");
        return;
    }
    _dlgView = [[SettingDlgViewController alloc]init];
    [self addChildViewController:_dlgView];
    [self.view addSubview:_dlgView.view];
    [self.view bringSubviewToFront:_dlgView.view];
    
    NSInteger width = [SettingDlgViewController obtainWidth];
    NSInteger height = [SettingDlgViewController obtainHeight];
    [_dlgView.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.view.center).offset(0);
        make.size.mas_equalTo(CGSizeMake(width, height));
    }];
}

- (void)startSendingProcess:(BOOL)toStarting {
    if(toStarting) {
        NSString* url = [[NSUserDefaults standardUserDefaults]objectForKey:WS_SERVER_KEY];
        if(!url){
            url = DEFAULT_WS_SERVER_ADDRESS;
        }
        NSString* token = getUserToken(YES);
        NSDictionary* param = [NSDictionary dictionaryWithObjectsAndKeys:token, @"token", @"IOS", @"device", nil];
        [[WebSocketManager shareManager] openWebsocket:url param:param];
    } else {
        [[WebSocketManager shareManager]closeWebSocket];
    }
}

- (void)sendData:(NSData *)data{
    [[WebSocketManager shareManager] sendData:data];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    [self setNeedsStatusBarAppearanceUpdate];
}

- (BOOL)prefersStatusBarHidden{
    return YES;
}

-(void)dealloc{
    [self.previewerAdapter stop];
}
@end
